classdef MinFinder290 < handle
    %MinFinder290 1D minimum finder
    %   We thought this up together in class
    
    properties
        F;              %function handle
        X;              %positions
        TolX=.001;      %Tolerance on X
        A;              %left interval edge
        B;              %right interval edge
        StepSize=.01;   %initial step size, changes during execution     
        X0;             %initial position
    end
    
    methods
        
        function finder290(obj) %The main min finder method
           
            dX=2*obj.TolX;
            obj.X(1)=obj.X0;
            ii=1;
            
            while dX>obj.TolX %keep going until we reach tolerance
               CurrentX=obj.X(ii); 
               TestX=obj.X(ii)+obj.StepSize;
               
               if obj.F(TestX) > obj.F(CurrentX) %Went too far- go back slower
                  obj.StepSize=-obj.StepSize/2; 
               end
               
               dX=abs(TestX-CurrentX);
               obj.X(ii+1)=TestX; %Keep track of where we are
               ii=ii+1;
            end            
        end
        
        function plot290(obj) %illustrates the procedure
            
           Xplot=linspace(obj.A,obj.B,100);
           Yplot=obj.F(Xplot);
           figure
           
           %plot function
           plot(Xplot,Yplot)
           xlabel('X') %always label axis!
           ylabel('F(X)')
           
           hold on
           
           %create a small increment in Y so plots don't overlap
           dY=(max(Yplot)-min(Yplot))/length(obj.X);
           
           %show the found  value as a dotted line 
           plot([obj.X(end) obj.X(end)],[min(Yplot) max(Yplot)],'k--')
           
           %plot all the line segments showing the steps
           for nn=2:length(obj.X)
               xtemp=[obj.X(nn-1) obj.X(nn)];
               ytemp=[nn*dY (nn+1)*dY];
               plot(xtemp,ytemp,'r')
               plot(obj.X(nn-1),nn*dY,'k.')
           end
           
           %Usually you should use a legend. 
           legend('F(X)','Found Min','Jump','Current X')
            
        end
        
    end
    
end

